package com.mop.app.service;

import com.mop.app.common.enums.AppBizEnums;
import com.mop.app.common.exception.BizException;
import com.mop.app.common.util.FileHandleUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Service
public class FileService {
    @Value("${smas.captrue.image.path}")
    private String captureImagePath;

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Value("${file.uri}")
    private String uri;

    private Set<String> types = new HashSet<>();

    @PostConstruct
    private void init() {
        types.add("image/jpeg");
        types.add("image/png");
        types.add("image/gif");
    }


    /**
     * 保存文件
     * @param multipartRequest
     * @return
     */
    public List<String> saveFile(MultipartHttpServletRequest multipartRequest) {
        Map<String, MultipartFile> files = multipartRequest.getFileMap();
        String path_deposit = uploadFolder + captureImagePath;

        List<String> urls = new ArrayList<>();
        for (Map.Entry<String, MultipartFile> entry : files.entrySet()) {
            try {
                MultipartFile multipartFile = entry.getValue();
                // 检查文件MIME类型
                String contentType = multipartFile.getContentType();
                AppBizEnums.ERROR_1010.assertTrue(types.contains(contentType));

                //重新生成文件名
                String fileName = entry.getValue().getOriginalFilename();

                fileName = FileHandleUtil.upload(entry.getValue().getInputStream(), path_deposit, fileName);
                urls.add(FileHandleUtil.getServerIPPort(multipartRequest) + uri + fileName);
            } catch (IOException e) {
                throw new BizException("9090", "文件读取异常");
            }
        }

        return urls;
    }
}
